﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;


/*
加速
 */
public class PropelDevice : Weapon {

	private float maxBuffer;//最大缓冲
	private float currBuffer;//当前缓冲
	private float everyBuffer;//每帧缓冲
	private float expendBuffer;//每帧消耗
	private float tempBuffer;//缓冲，用于恢复和消耗血量
	private float propelSpeed;//加速时的速度
	private float propelSpeedTemp;


	private GameObject gun;
	private GameObject target;
	private bool isUsing = false;//当前装置是否作用

	// Use this for initialization
	void Start () {
		Init();
		AttackTargetManager.SendMsgToDevice += ChangeState;
	}
	
	void Update () {
		foreach (Transform child in target.transform)
		{
			if(child.gameObject.name != "heroMinRange")
			{
				child.transform.position = target.transform.position;
			}
		}
	}

	void FixedUpdate()
	{
		RecoverAndExpendBuffer();
		if(currBuffer <= 0 && isUsing)
		{
			isUsing = false;
		}
		Propel();
	}

	private void Init()
	{
		maxBuffer = 1000;
		currBuffer = maxBuffer;
		everyBuffer = 1;
		expendBuffer = 2;
		propelSpeed = 0;
	}


	private void Propel()
	{
		if(isUsing)
		{
			target.GetComponent<Rigidbody2D>().velocity = target.transform.up * target.GetComponent<Rigidbody2D>().velocity.magnitude;
		}
		else
		{
			print("propelSpeedTemp--->" + propelSpeedTemp);
			if(propelSpeedTemp > 0)
			{
				print("two");
				--propelSpeedTemp;	
				target.GetComponent<Rigidbody2D>().velocity = target.transform.up * target.GetComponent<Rigidbody2D>().velocity.magnitude;			
				target.GetComponent<Rigidbody2D>().velocity -= new Vector2(target.transform.up.x, target.transform.up.y);
			}

			

				// target.GetComponent<Rigidbody2D>().velocity -= new Vector2(target.transform.up.x*propelSpeed, target.transform.up.y*propelSpeed);
		
		}
	}


	public void RecoverAndExpendBuffer()
	{
		if(!isUsing)
		{
			tempBuffer = currBuffer + everyBuffer;
			if(tempBuffer < maxBuffer)
			{
				currBuffer = tempBuffer;
			}
			else
			{
				currBuffer = maxBuffer;
			}
			tempBuffer = 0;
		}
		else
		{
			tempBuffer = currBuffer - expendBuffer;
			if(tempBuffer > 0)
			{
				currBuffer = tempBuffer;
			}
			else
			{
				currBuffer = 0;
			}
			tempBuffer = 0;
		}
	}

	public void SetGun(GameObject gun)
	{
		this.gun = gun;
	}

	public void SetTarget(GameObject target)
	{
		this.target = target;
	}

	

	private void ChangeState(string weaponName, string gunName)
	{
		print(weaponName);
		if(weaponName == "PropelDevice" && gunName == gun.gameObject.name)
		{
			
			print("接收到了");
			if(isUsing)
			{
				isUsing = false;
			
			}
			else
			{
				
				propelSpeed = 20;
				propelSpeedTemp = propelSpeed;
				target.GetComponent<Rigidbody2D>().velocity += new Vector2(target.transform.up.x*propelSpeed, target.transform.up.y*propelSpeed) ;
				isUsing = true;
			}
		}
	}
}
